import {resolve} from "url";
import {rejects} from "assert";
import {msg} from '@/utils/index'
import {getToken} from './getToken';
var Fly = require("flyio/dist/npm/wx")
var qs = require('qs');
import store from '@/store'

var fly = new Fly

//添加req拦截器
fly.interceptors.request.use((config, promise) => {
  //给所有请求添加自定义header


  wx.showLoading({
    title: '加载中',
    mask: true
  })
  config.headers["X-Tag"] = "flyio";
  store.dispatch("set_loading",false);

  return config;
})
////添加res拦截器
fly.interceptors.response.use(
  res => {
    wx.hideLoading();
    store.dispatch("set_loading",true);   //响应成功，loading改为true；

  },
  err => {
    store.dispatch("set_loading",true);   //响应成功，loading改为true；
    
    switch (true) {
      case err.status == 666:
        msg(err.response.data.data || "没有权限,请联系管理员添加权限！")
        return err.response.data.data || "没有权限,请联系管理员添加权限！";
        break;
      case err.status == 777:
        msg(err.response.data.data || "身份信息失效,请重新登录！")
        return err.response.data.data || "身份信息失效,请重新登录！";
        break;
      case err.status == 999:
        msg(err.response.data.data || "用户不存在！")
        return err.response.data.data || "用户不存在！";
        break;
      // case err.response.data.success != true:
      //   msg(err.response.data.err || "系统正忙，请稍后再试")
      //   return err.response.data.err || "系统正忙，请稍后再试！";
      default:
        msg(err.message)
        break;
    }
  }
)

//配置请求基地址
fly.config = {
  baseURL: process.env.APP_ORIGIN,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    // 'x-lsc-AthToken':getToken()
  },
  timeout: 30000, // 超时
}

export default {
  post: (url, data) => {
    return fly.post(url, qs.stringify(data), {
      timeout: 30000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'x-lsc-AthToken':getToken()
      }
    })
  },
  postJson: (url, data) => {
    return fly.post(url, data, {
      timeout: 30000,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'x-lsc-AthToken':getToken()
      }
    })
  },
  get: (url, data) => {
    return fly.get(url, data, {
      timeout: 30000,
      headers: {
        'x-lsc-AthToken':getToken()
      }
    })
  },
  put: (url, data) => {
    return fly.put(url, data, {
      timeout: 30000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        'x-lsc-AthToken':getToken()
      }
    })
  },
  putJson: (url, data) => {
    return fly.put(url, qs.stringify(data), {
      timeout: 30000,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'x-lsc-AthToken':getToken()
      }
    })
  }

}
